<template>
  <div class="zhutui">
    <a-card style="margin-top: 24px" :bordered="false" :body-style="{padding: '24px'}">
      <div class="extra-wrap" slot="title">
        <a-date-picker v-model="date" :disabled-date="disabledDate" @change="getData" :allowClear="false" />
      </div>
      <div class="reload" slot="extra" @click="getData">
        <a-progress type="circle" :percent="reloadPercent" :width="26">
          <template #format>
            <a-icon type="reload" :spin="loading"/>
          </template>
        </a-progress>
      </div>
      <div class="wrap">
        <div class="total">
          <a-card-grid class="grid" v-for="(item) in totalData" :key="item.label" :hoverable="false">
            <div class="label">{{item.label}}</div>
            <countTo v-if="item.value.toString().indexOf('.') != -1" :startVal='0' :endVal='parseFloat((item.value || 0))' :duration='800' :decimals="2"></countTo>
            <countTo v-else :startVal='0' :endVal='parseFloat((item.value || 0))' :duration='800' :decimals="0"></countTo>
          </a-card-grid>
        </div>
        <div class="table">
          <a-table
            rowKey="time"
            :columns="columns"
            :loading="loading"
            :data-source="data"
            :pagination="false"
            bordered
            size="middle"
            :scroll="{ x: 'calc(700px + 50%)', y: 550 }"
          >
            <template v-slot:content="scope">
              <div v-html="scope"></div>
            </template>
          </a-table>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment';
import countTo from 'vue-count-to';
import {live_Minute_list, live_Minute_column, live_Minute_total} from '@/api/dianshang/dianshang'


export default {
  data() {
    return {
      date: moment(),
      chartTimeSelect: 1,
      labelAlign: 'right',
      loading: false,
      reloadTime: 60, // 自动刷新时间（秒）
      reloadChangeTime: 0,
      reloadIndex: null, // 用于关闭setInterval
      totalData: [],
      data:[],
      columns:[],
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.getData()
    },
    getData() {
      this.loading = true
      this.startReload()
      const date = moment(this.date).format("YYYY-MM-DD")
      live_Minute_list({date}).then((res_list) => {
        if (res_list.errcode == 0) {
          this.data = res_list.data
        }
        live_Minute_column({}).then((res_column) => {
          if (res_column.errcode == 0) {
            let res_column_data = res_column.data
            let columns = this.setColumn(res_column_data)
            this.columns = columns
          }
          live_Minute_total({date}).then((res_total) => {
            if (res_column.errcode == 0) {
              this.totalData = res_total.data
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          });
        }).catch(() => {
          this.loading = false
        });
      }).catch(() => {
        this.loading = false
      });
    },
    startReload() {
      this.reloadIndex && clearInterval(this.reloadIndex)
      this.reloadChangeTime = this.reloadTime
      this.reloadIndex = setInterval(() => {
        if (this.reloadChangeTime == 0) {
          this.getData()
          this.reloadChangeTime = this.reloadTime
        } else {
          this.reloadChangeTime--;
        }
      }, 1000);
    },
    setColumn(arr, mod = 1, color='') {
      // mod：1为第一层 2位第二层（children层）
      const column = []
      for (let idx in arr) {
        const item = arr[idx]
        if (item.dataIndex) {
          const o = {
            title: item.title,
            dataIndex: item.dataIndex,
            width: this.getColumnWidth(item.dataIndex, mod),
          }
          if (item.dataIndex == "stat_datetime") {
            o.dataIndex = 'time'
            o.fixed = 'left'
          }
          if (color == '') {
            this.setColumnColor(o, item.color)
          } else {
            this.setColumnColor(o, color)
          }
          if (mod == 2) {
            o.scopedSlots = { customRender: 'content' }
          }
          if (item.children) {
           o.children = this.setColumn(item.children, 2, item.color)
          }
          column.push(o)
        } else {
          const o = {
            width: item.width,
          }
          this.setColumnColor(o, '#fff')
          column.push(o)
        }
      }
      return column
    },
    getColumnWidth(dataIndex, mod) {
      switch (dataIndex) {
        case "stat_datetime":
          return "120px"
        default:
          return mod == 1 ? "420px" : "80px"
      }
    },
    setColumnColor(item, color) {
      item.customHeaderCell = () => {
        return {
          style: {
            background: color,
          }
        }
      } 
      item.customCell = () => {
        return {
          style: {
            background: color
          },
        }
      }
    },
    getColumnColor(idx) {
      const color_list = ['#f0a1a8', '#a7a8bd', '#93b5cf', '#9eccab', '#f6c430']
      const l = color_list.length
      const x = Math.floor(idx / color_list.length)
      console.log(idx, x);
      if (x > 0) {
        idx = idx - l * x
      }
      console.log(idx, color_list[idx]);
      return {
        style: {
          background: color_list[idx],
        }
      }
    },
    disabledDate(current){
      return current && ( current < moment().endOf('day').add(-100, 'days') || current > moment().endOf('day').add('days')) ;
    },
  },
  computed: {
    reloadPercent() {
      return Math.ceil(100 - (this.reloadChangeTime / this.reloadTime) * 100)
    }
  },
  beforeDestroy() {
    clearInterval(this.reloadIndex)
  },
  components:{
    countTo,
  }
}
</script>

<style lang="less" scoped>
.search{
  background-color: #ffffff;
  padding: 12px;
  border-radius: 8px;
  margin-top: 20px;
}
.reload{
  cursor: pointer;  
}
.zhutui{
  .wrap{
    max-height: 750px;
    .table{
    }
    .total{
      overflow: hidden;
      .grid{
        display: flex;
        flex-direction: column;
        font-size: 16px;
        .label{
          margin-bottom: 10px;
        }
      }
    }
  }
}
</style>